package com.medsoft.drpcp.client;

import static com.medsoft.drpcp.meta.DrpcpMetaConstant.NODE_NAME_LOCALSERVICE;

import java.text.MessageFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.remoting.support.RemoteAccessor;

import com.medsoft.base.utils.CRCUtils;
import com.medsoft.base.utils.EncryptUtils;
import com.medsoft.base.utils.JsonUtils;
import com.medsoft.base.utils.UUIDUtils;
import com.medsoft.drpcp.DrpcpRouter;
import com.medsoft.drpcp.GlobalConfig;
import com.medsoft.drpcp.RouteItem;
import com.medsoft.drpcp.ServiceDefinition;
import com.medsoft.drpcp.ServiceDefinitionContainer;
import com.medsoft.drpcp.exception.DrpcpException;
import com.medsoft.drpcp.meta.DrpcpHead;
import com.medsoft.drpcp.meta.DrpcpHeadConstant;

public class RpcServiceProxyImpl extends RemoteAccessor implements InitializingBean,MethodInterceptor,FactoryBean<Object> {
	static final Logger logger = LoggerFactory.getLogger(RpcServiceProxyImpl.class);
	private Object serviceProxy;
	
	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		logger.debug("calling proxy class: " + invocation.getMethod().getDeclaringClass());
		logger.debug("calling proxy method: " + invocation.getMethod().getName());
		ServiceDefinition serviceDef = ServiceDefinitionContainer.getServiceByMethodName(invocation.getMethod().getName());
		logger.debug("Drpcp service id: " + serviceDef.getServiceId());
		logger.debug("Drpcp service target server: " + serviceDef.getNodeName());
		//判断是否为动态路由
		if(GlobalConfig.isDynamicRouteEnable) {
			DrpcpHead head = ((DrpcpHead)invocation.getArguments()[0]);
			if(StringUtils.isNotEmpty(head.getDrpcpVersion())
					|| StringUtils.isNotEmpty(head.getDrpcpCorpId())) {
				for(RouteItem routeItem : GlobalConfig.routeItems) {
					if (Pattern.matches(routeItem.getServiceId().replace("*", "[0-9]+").replace("?", "[0-9]"), serviceDef.getServiceId())
							&& Pattern.matches(routeItem.getCorpId().replace("*", "\\S+").replace("?", "\\S"), head.getDrpcpCorpId() == null ? "*" : head.getDrpcpCorpId())
							&& Pattern.matches(routeItem.getVersion().replace("*", "\\S+").replace("?", "\\S"), head.getDrpcpVersion() == null ? "*" : head.getDrpcpVersion())
							&& Pattern.matches(routeItem.getSubSystemId().replace("*", "[0-9]+").replace("?", "[0-9]"), serviceDef.getSubSystemId())
							&& Pattern.matches(routeItem.getSystemId().replace("*", "[0-9]+").replace("?", "[0-9]"), serviceDef.getSystemId()) ){
						serviceDef.setNodeName(routeItem.getNodeName());
						break;
					}
				}
			}
		}
		String args = JsonUtils.toJson(invocation.getArguments()[0]);
		if(GlobalConfig.encrypt) {
			args = EncryptUtils.aesEncrypt(args);
		}
		if (serviceDef.getNodeName().equals(NODE_NAME_LOCALSERVICE)) {
			throw new DrpcpException("drpcp service [" + serviceDef.getServiceId() + "]'s route is set to local, but there is no implemation or export path is incorrect!");
		} else if (serviceDef.getNodeName().equals("")) {
			throw new DrpcpException("drpcp service [" + serviceDef.getServiceId() + "] is set with incorrect route, cannot forward!");
		} else {
			logger.debug(MessageFormat.format("preparing to call drpcp service [{0}] {1} {2} {3} ...",
					serviceDef.getServiceId(),
					invocation.getMethod().getDeclaringClass(),
					invocation.getMethod().getName(),
					args));
			String drpcpMsgId = UUIDUtils.uuid();
			String crc32 = String.valueOf(CRCUtils.getCRC32Value(args));
			String retJsonStr = DrpcpRouter.call(serviceDef.getServiceId(),drpcpMsgId,crc32, args, serviceDef);
			if(GlobalConfig.encrypt) {
				retJsonStr = EncryptUtils.aesDecrypt(args);
			}
			Object retObj = JsonUtils.deserialize(retJsonStr,serviceDef.getRetType());
			if (((DrpcpHead)retObj).getDrpcpErrorNo() != DrpcpHeadConstant.ERROR_NO_SUCCESS) {
				throw new DrpcpException("some exception throwed during call the drpcp service[" + serviceDef.getServiceId() + "]. cause: drpcpErrorNo=" + ((DrpcpHead)retObj).getDrpcpErrorNo() + ",drpcpErrorInfo=" + ((DrpcpHead)retObj).getDrpcpErrorInfo());
			}
			return retObj;
		}
	}

	@Override
	public Object getObject() throws Exception {
		return serviceProxy;
	}

	@Override
	public Class<?> getObjectType() {
		return super.getServiceInterface();
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		this.serviceProxy = new ProxyFactory(super.getServiceInterface(),this).getProxy();
	}
	
	public static void main(String[] args) {
		/*Pattern p = Pattern.compile("12[0-9][0-9]90"); 
        Matcher m = p.matcher("12990"); 
        boolean flg = m.matches(); */
        System.out.println(Pattern.matches("\\S","v1")); 
	}
}
